package domoticus;

import Cosm.Cosm;
import Cosm.CosmException;
import Cosm.Datapoint;
import Cosm.Datastream;
import Cosm.Feed;
import Cosm.Interval_type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBConnectionCon {

    private static String API_KEY = "0EvyVoy3p9kQIBJ5-7LPFbWoDxGSAKx3dTMvdUh3blRYRT0g";
    Cosm cosm = null;
    Feed feed = null;

    public DBConnectionCon() {
        this.cosm = new Cosm(API_KEY);

    }

    public Integer getFeedId(String username, String room) {

        Integer feedID = null;
        Feed feed[] = getUsersFeeds(username);
        Comparator<String> comparadorFeeds = new ComparatorFeeds();
        for (Feed f : feed) {
            if (comparadorFeeds.compare(room, f.getTitle()) == 0) {
                feedID = f.getId();
                break;
            } else {
                new FeedNoValidoException("El sensor seleccionado no es correcto");
            }

        }
        return feedID;
    }

    public String getCurrentValue(String username, Integer feedid, String datastream) {
        String value = null;
        try {
            Datastream thread = cosm.getDatastream(feedid, datastream);
            value = thread.getCurrentValue();

        } catch (CosmException ex) {

            Logger.getLogger(DBConnectionCon.class.getName()).log(Level.SEVERE, null, ex);
        }
        return value;


    }

    public Feed[] getUsersFeeds(String username) {


        Feed feeds[] = null;
        try {
            feeds = cosm.getFeeds(null, null, null, username, null, null,
                    null, null);
        } catch (CosmException e) {

            e.printStackTrace();
        }
        return feeds;
    }
    
    public Datastream[] getDatastreams(Integer feedId){
        Datastream [] data=null;
        try {
            data = cosm.getDatastreams(feedId);
        } catch (CosmException ex) {
            Logger.getLogger(DBConnectionCon.class.getName()).log(Level.SEVERE, null, ex);
        }
        return data;
    
    }
     public List<String> datastreamToString(Datastream data[]) {

        List<String> datas = new ArrayList<>(data.length);
        for (int i = 0; i < data.length; i++) {
            datas.add(data[i].getId());
        }
        return datas;

    }

    public List<String> feedsToString(Feed feed[]) {

        List<String> feeds = new ArrayList<>(feed.length);
        for (int i = 0; i < feed.length; i++) {
            feeds.add(feed[i].getTitle());
        }
        return feeds;

    }

    public String checkDuplicateFeeds(String feed) {
        String check = "correct";
        cosm = new Cosm(API_KEY);
        List<String> feeds = feedsToString(getUsersFeeds("samunake"));
        Comparator<String> comparadorFeeds = new ComparatorFeeds();
        for (String f : feeds) {
            if (comparadorFeeds.compare(f, feed) == 0) {
                check = "no_correct";
            }
        }
        return check;
    }
    
    public void addFeed(String feedName) throws CosmException {

        cosm = new Cosm(API_KEY);
        Feed feed = new Feed();
        feed.setTitle(feedName);
        if (checkDuplicateFeeds(feedName).equals("correct")) {
            cosm.createFeed(feed);
        } else {
            throw new FeedNoValidoException(
                    "El Feed introducido ya existe. Proporcione otro nombre");
        }
    }
    
    public static Datastream[] showDatastreams(Feed feed) {

        Datastream[] datas = feed.getDatastreams();
        return datas;
    }

    public static Double[] getValues(Cosm pachube, Feed feedid,
            String datastreamid, String fechaInicio, String fechaFinal, Integer porPagina) {
        Double valores[] = null;
        Datapoint datapoints[] = null;

        try {
            datapoints = pachube.getDatapoints(feedid.getId(), datastreamid, fechaInicio, fechaFinal, "20hour", 3600, null, Interval_type.discrete, porPagina, null);
            String values[] = new String[datapoints.length];
            valores = new Double[datapoints.length];

            for (int i = 0; i < datapoints.length; i++) {

                values[i] = datapoints[i].getValue();
                valores[i] = Double.parseDouble(values[i]);
            }
        } catch (CosmException e) {

            e.printStackTrace();
        }
        return valores;
    }

    public Cosm getApi() {
        return cosm;
    }

    public static void main(String arsg[]) {


        DBConnectionCon con = new DBConnectionCon();


//        try {
//            Feed f = pachube.getFeed(1631431830);

        System.out.println(con.getUsersFeeds("samunake"));


//            Double data[] = getValues(pachube, f, "Temperature", "23/05/2013", null, 1000);
//            System.out.println(Arrays.toString(data));
//            System.out.println(data.length);
//            Datastream d = pachube.getDatastream(f.getId(), "Temperature");
//            System.out.println(d.getAt());
//		Datastream results [] = showDatastreams(f );
//		System.out.println(Arrays.toString(results));

//        } catch (CosmException e) {
//            e.printStackTrace();
//        }
        //
//			Feed f[] = getUsersFeeds("samunake");
//			System.out.println(Arrays.toString(f));
//			
//				Datastream data []=pachube.getDatastreams(f[0].getId());
//				System.out.println(Arrays.toString(data));
//				Datastream nuevo = new Datastream();
//				nuevo.setId("nuevo");
//				nuevo.setCurrentValue("5648988");
//				data[1]= nuevo;
//				data[4]=data[1];
//				pachube.updateFeed(f[0]);
//				try{
//					pachube = new Cosm(API_KEY);
//					Datastream data = new Datastream();
//					data.setId("Temperatura");
//					pachube.updateDatastream(f[0].getId(), "Conexi�n_Ok", data);
////					pachube.getDatastream(f[0].getId(), "Vamos_Co�o").setId("Vamos_Rafa");
//
//				
//
//				//pachube.deleteDatastream(f[0].getId(), "Conexi�n_Ok");
//		} catch (CosmException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
        //prueba de crear feed
//			try {
//				 Feed f = new Feed();
//                 f.setTitle("Domoticus");
//                 f.setId(1598825325);
//                 
//                 Datastream a[]= showDatastreams(f);
//                 a[0].setAt("temperatura2");


//            
//                 a[0].setId("Temperatura");
//                 a[0].setMaxValue("100");
//                 a[0].setMinValue("0");
//                 a[0].setCurrentValue("30");
//                 
//                 a[1].setId("Luminosidad");
//                 a[1].setMaxValue("100");
//                 a[1].setMinValue("0");
//                 a[1].setCurrentValue("30");
//                
//                 a[2].setId("Humedad");
//                 a[2].setMaxValue("100");
//                 a[2].setMinValue("0");
//                 a[2].setCurrentValue("30");
//                
//                 a[3].setId("Check_Error");
//                 a[3].setCurrentValue("ok");
//                 
//                 a[4].setId("De_sobra");
//                 a[4].setCurrentValue("ok");
//                 
// 				pachube = new Cosm(API_KEY);
// 				f.setDatastreams(a);
//                 pachube.updateFeed(f);
//                 //The Feed 'f' is does not represent the feed on pachube any
////                 // Changes made to this object will not alter the online feed.
////               
//			
//			} catch (CosmException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
////			


    }
}
